package com.xunk.auth.exception;

import com.xunk.common.core.exception.BaseException;
import com.xunk.common.core.utils.DataUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.oauth2.provider.error.DefaultWebResponseExceptionTranslator;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * OAuth2 自定义异常处理
 *
 * @author ruoyi
 */
public class CustomWebResponseExceptionTranslator extends DefaultWebResponseExceptionTranslator {
    @Override
    public ResponseEntity<OAuth2Exception> translate(Exception e) {
        String message;
        Throwable cause = e.getCause();
        if (DataUtils.isNotEmpty(cause)) {
            if (cause instanceof BaseException) {
                message = ((BaseException) cause).getDefaultMessage();
            } else {
                message = cause.getMessage();
            }
        } else {
            message = e.getMessage();
        }
        if (DataUtils.isEmpty(message)) {
            message = "系统异常，请稍后重试~";
        }
        return ResponseEntity.status(HttpStatus.OK).body(new CustomOauthException(message));
    }
}
